using UnityEngine;
using UI = UnityEngine.UI;
using UnityEngine.UIElements;

public class PrefabToVisualElement
{
    public static VisualElement Convert(GameObject uiPrefab)
    {
        if (uiPrefab == null) return null;
        
        var rootElement = CreateVisualElementFromGameObject(uiPrefab);
        ConvertRecursive(uiPrefab.transform, rootElement);
        
        return rootElement;
    }
    
    private static void ConvertRecursive(Transform parentTransform, VisualElement parentElement)
    {
        foreach (Transform child in parentTransform)
        {
            var childElement = CreateVisualElementFromGameObject(child.gameObject);
            if (childElement != null)
            {
                parentElement.Add(childElement);
                ConvertRecursive(child, childElement);
            }
        }
    }
    
    private static VisualElement CreateVisualElementFromGameObject(GameObject gameObject)
    {
        VisualElement element = null;
        
        // 检查组件并创建对应的 VisualElement
        if (gameObject.GetComponent<UI.Button>() != null)
        {
            element = ConvertButton(gameObject);
        }
        else if (gameObject.GetComponent<UI.Image>() != null)
        {
            element = ConvertImage(gameObject);
        }
        else if (gameObject.GetComponent<UI.Text>() != null)
        {
            element = ConvertText(gameObject);
        }
        else if (gameObject.GetComponent<UI.Slider>() != null)
        {
            element = ConvertSlider(gameObject);
        }
        else if (gameObject.GetComponent<UI.Toggle>() != null)
        {
            element = ConvertToggle(gameObject);
        }
        else if (gameObject.GetComponent<UI.ScrollRect>() != null)
        {
            element = ConvertScrollView(gameObject);
        }
        else
        {
            // 默认容器
            element = new VisualElement();
            element.name = gameObject.name;
        }
        
        // 应用通用样式
        ApplyCommonStyles(gameObject, element);
        
        return element;
    }
    
    private static Button ConvertButton(GameObject gameObject)
    {
        var button = gameObject.GetComponent<UI.Button>();
        var uiButton = new Button();
        uiButton.name = gameObject.name;
        
        // 获取按钮文本
        var textComponent = gameObject.GetComponentInChildren<UI.Text>();
        if (textComponent != null)
        {
            uiButton.text = textComponent.text;
        }
        
        // 复制点击事件（需要手动处理）
        uiButton.clicked += () =>
        {
            button.onClick?.Invoke();
        };
        
        return uiButton;
    }
    
    private static VisualElement ConvertImage(GameObject gameObject)
    {
        var image = gameObject.GetComponent<UI.Image>();
        var uiImage = new VisualElement();
        uiImage.name = gameObject.name;
        
        // 设置背景图片（需要处理 Sprite 到 Texture2D 的转换）
        if (image.sprite != null)
        {
            // 注意：这里需要适当的纹理转换
            uiImage.style.backgroundImage = new StyleBackground(image.sprite);
        }
        
        uiImage.style.backgroundColor = new StyleColor(image.color);
        
        return uiImage;
    }
    
    private static Label ConvertText(GameObject gameObject)
    {
        var text = gameObject.GetComponent<UI.Text>();
        var uiLabel = new Label();
        uiLabel.name = gameObject.name;
        uiLabel.text = text.text;
        
        // 应用文本样式
        uiLabel.style.color = new StyleColor(text.color);
        uiLabel.style.fontSize = new StyleLength(text.fontSize);
        uiLabel.style.unityFontStyleAndWeight = new StyleEnum<FontStyle>(text.fontStyle);
        uiLabel.style.unityTextAlign = new StyleEnum<TextAnchor>(text.alignment);
        
        return uiLabel;
    }
    
    private static Slider ConvertSlider(GameObject gameObject)
    {
        var slider = gameObject.GetComponent<UI.Slider>();
        var uiSlider = new Slider();
        uiSlider.name = gameObject.name;
        uiSlider.lowValue = slider.minValue;
        uiSlider.highValue = slider.maxValue;
        uiSlider.value = slider.value;
        
        // 注册值改变事件
        uiSlider.RegisterValueChangedCallback(evt =>
        {
            slider.value = evt.newValue;
            slider.onValueChanged?.Invoke(evt.newValue);
        });
        
        return uiSlider;
    }
    
    private static Toggle ConvertToggle(GameObject gameObject)
    {
        var toggle = gameObject.GetComponent<UI.Toggle>();
        var uiToggle = new Toggle();
        uiToggle.name = gameObject.name;
        uiToggle.value = toggle.isOn;
        uiToggle.label = gameObject.name;
        
        // 注册值改变事件
        uiToggle.RegisterValueChangedCallback(evt =>
        {
            toggle.isOn = evt.newValue;
            toggle.onValueChanged?.Invoke(evt.newValue);
        });
        
        return uiToggle;
    }

    private static ScrollView ConvertScrollView(GameObject gameObject)
    {
        var scrollRect = gameObject.GetComponent<UI.ScrollRect>();
        var uiScrollView = new ScrollView();
        uiScrollView.name = gameObject.name;

        // 设置滚动方向
        uiScrollView.horizontalScrollerVisibility = scrollRect.horizontal ?
          ScrollerVisibility.Auto : ScrollerVisibility.Hidden;
        uiScrollView.verticalScrollerVisibility = scrollRect.vertical ?
            ScrollerVisibility.Auto : ScrollerVisibility.Hidden;

        return uiScrollView;
    }
    
    private static void ApplyCommonStyles(GameObject gameObject, VisualElement element)
    {
        var rectTransform = gameObject.GetComponent<RectTransform>();
        if (rectTransform != null)
        {
            // 位置和大小
            element.style.width = new StyleLength(rectTransform.rect.width);
            element.style.height = new StyleLength(rectTransform.rect.height);
            
            // 布局
            element.style.position = new StyleEnum<Position>(Position.Absolute);
            element.style.left = new StyleLength(rectTransform.anchoredPosition.x);
            element.style.top = new StyleLength(-rectTransform.anchoredPosition.y);
            
            // 边距和填充
            element.style.marginLeft = new StyleLength(rectTransform.offsetMin.x);
            element.style.marginTop = new StyleLength(-rectTransform.offsetMin.y);
            element.style.marginRight = new StyleLength(-rectTransform.offsetMax.x);
            element.style.marginBottom = new StyleLength(rectTransform.offsetMax.y);
        }
        
        // 背景颜色（如果有 Image 组件）
        var image = gameObject.GetComponent<UI.Image>();
        if (image != null)
        {
            element.style.backgroundColor = new StyleColor(image.color);
        }
    }
}